
import shutil
import sys
from typing import Dict, List
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QFileDialog,
    QLabel, QPushButton, QHBoxLayout, QVBoxLayout,
    QWidget, QScrollArea, QCheckBox, QDialogButtonBox
)
from PyQt6.QtGui import (QPixmap, QImage)
from PyQt6.QtCore import Qt
import os
import cv2

from video_utils import VideoFile
from video_file_find_duplicate import get_duplicate_video_file

class VideoSelector(QMainWindow):
    def __init__(self):
        super().__init__()
        self.selected_videos: Dict[str, List[VideoFile]] = {}
        self.base_path = None
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("视频选择器")
        self.setGeometry(100, 100, 1200, 600)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)

        btn_load = QPushButton("加载视频文件夹")
        btn_load.clicked.connect(self.load_videos)
        main_layout.addWidget(btn_load)

        self.scroll_area = QScrollArea()
        scroll_content = QWidget()
        self.grid_layout = QVBoxLayout(scroll_content)
        self.scroll_area.setWidget(scroll_content)
        self.scroll_area.setWidgetResizable(True)
        main_layout.addWidget(self.scroll_area)

        btn_box = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel
        )
        btn_box.accepted.connect(self.confirm_selection)
        btn_box.rejected.connect(self.cancel_selection)
        main_layout.addWidget(btn_box)

    def load_videos(self):
        dir_path = os.path.normpath(QFileDialog.getExistingDirectory(self, "选择视频目录"))
        if not dir_path:
            return
        self.base_path = dir_path
        for i in reversed(range(self.grid_layout.count())): 
            self.grid_layout.itemAt(i).widget().deleteLater()

        duplicate_list = get_duplicate_video_file(dir_path)
        for key, videos in duplicate_list.items():
            self.add_duplicate_video_item(key, videos)

    def get_video_thumbnail(self, video_path):
        cap = cv2.VideoCapture(video_path)
        ret, frame = cap.read()
        cap.release()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            height, width, channel = frame.shape
            bytes_per_line = 3 * width
            return QPixmap.fromImage(
                QImage(
                    frame.data, width, height, 
                    bytes_per_line, QImage.Format.Format_RGB888
                )
            )
        return QPixmap()
    
    def add_duplicate_video_item(self, key: str, videos: List[VideoFile]):
        item = QWidget()
        layout = QHBoxLayout(item)

        chk_box = QCheckBox(checked=True)
        chk_box.stateChanged.connect(
            lambda state, k=key, v=videos: self.toggle_selection(k, v, state)
        )
        chk_box.setFixedSize(80, 60)
        layout.addWidget(chk_box)
        self.toggle_selection(key, videos, Qt.CheckState.Checked.value)

        for i in videos:
            v_widget = QWidget()
            v_layout = QVBoxLayout(v_widget)
            thumbnail = self.get_video_thumbnail(i.path).scaled(
                200, 150, Qt.AspectRatioMode.KeepAspectRatio
            )
            lbl_thumb = QLabel()
            lbl_thumb.setPixmap(thumbnail)
            v_layout.addWidget(lbl_thumb)
            v_layout.addWidget(QLabel(os.path.basename(i.path)))
            v_widget.setFixedSize(300, 180)
            layout.addWidget(v_widget)

        # layout.addWidget(QLabel(os.path.basename(video_path)))
        self.grid_layout.addWidget(item)

    def toggle_selection(self, key, videos, state):
        if state == Qt.CheckState.Checked.value:
            self.selected_videos[key] = videos
        else:
            self.selected_videos.pop(key, None)

    def confirm_selection(self):
        print("已选择视频:", self.selected_videos)
        tmp_path = os.path.join(self.base_path, "tmp")
        os.makedirs(tmp_path, exist_ok=True)

        count = 1
        for _, videos in self.selected_videos.items():
            print(f"删除中，当前处理第{count}/{len(self.selected_videos)}个")
            count += 1
            size_list = [(x.path, os.path.getsize(x.path)) for x in videos]
            target_list = sorted(size_list, key=lambda x: (len(x[0]), -x[1]))
            for i, _ in target_list[1:]:
                full_name = os.path.basename(i)
                shutil.move(i, os.path.join(tmp_path, full_name))
                print(f"正在临时删除文件{i}, 保留的文件为{target_list[0][0]}")
        self.close()

    def cancel_selection(self):
        self.selected_videos.clear()
        self.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = VideoSelector()
    window.show()
    sys.exit(app.exec())
